<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <header class="chat-header">
      <div class="avatar">
        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 18.5C15.5899 18.5 18.5 15.5899 18.5 12C18.5 8.41015 15.5899 5.5 12 5.5C8.41015 5.5 5.5 8.41015 5.5 12C5.5 15.5899 8.41015 18.5 12 18.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M15.5 8C15.5 6.23858 13.7614 4.5 12 4.5C10.2386 4.5 8.5 6.23858 8.5 8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M19.0711 4.92893C21.9022 7.76 21.9022 12.24 19.0711 15.0711C16.2399 17.9022 11.7599 17.9022 8.92883 15.0711" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </div>
      <h1>AI 智能助手</h1>
      <div class="header-controls">
        <button class="control-btn" @click="clearChat">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M6 19L17.94 7.06006" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M18 19L6.06006 7.06006" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
      </div>
    </header>

    <!-- 聊天内容区域 -->
    <main class="chat-messages" ref="chatContainer">
      <!-- 初始提示信息 -->
      <div v-if="messages.length === 0" class="empty-state">
        <p>开始与AI助手聊天吧</p>
        <p class="subtext">它可以帮助你解答问题、提供建议</p>
      </div>

      <!-- 消息列表 -->
      <div v-for="(msg, index) in messages" :key="index" class="message-wrapper">
        <!-- 用户消息 -->
        <div v-if="msg.sender === 'user'" class="message user-message">
          <div class="message-content">
            <div class="message-bubble">
              <p>{{ msg.content }}</p>
            </div>
            <div class="message-avatar user-avatar">
              <img :src="getUserAvatar(msg.avatarId)" alt="用户头像" class="avatar-img">
            </div>
          </div>
        </div>

        <!-- AI消息 -->
        <div v-else class="message ai-message">
          <div class="message-content">
            <div class="message-avatar ai-avatar">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 18.5C15.5899 18.5 18.5 15.5899 18.5 12C18.5 8.41015 15.5899 5.5 12 5.5C8.41015 5.5 5.5 8.41015 5.5 12C5.5 15.5899 8.41015 18.5 12 18.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M15.5 8C15.5 6.23858 13.7614 4.5 12 4.5C10.2386 4.5 8.5 6.23858 8.5 8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M19.0711 4.92893C21.9022 7.76 21.9022 12.24 19.0711 15.0711C16.2399 17.9022 11.7599 17.9022 8.92883 15.0711" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <div class="message-bubble">
              <p v-if="!msg.loading" v-html="formatMessage(msg.content)"></p>
              <div v-else class="typing-indicator">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 输入区域 -->
    <footer class="chat-input">
      <form @submit.prevent="sendMessage">
        <textarea
            v-model="inputMessage"
            placeholder="输入消息..."
            @keydown.enter.exact="sendMessage"
            @keydown.enter.shift="inputMessage += '\n'"
            :disabled="isLoading"
        ></textarea>
        <button type="submit" :disabled="!inputMessage.trim() || isLoading">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M22 2L11 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M22 2L15 22L11 13L2 9L15 22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
      </form>
    </footer>
  </div>
</template>

<script>
// 导入API接口
import { receiveMessage2 } from '../api/ai.js';
import {jwtDecode} from "jwt-decode";
import axios from "axios"; // 请根据实际api文件路径调整

export default {

  data() {
    return {
      messages: [],        // 聊天消息列表
      inputMessage: '',    // 输入框内容
      isLoading: false,    // 是否正在加载
      chatContainer: null, // 聊天容器DOM引用
      avatarCache: {},
      defaultAvatar: "https://picsum.photos/42/42",
      avatarId:null
    };
  },
  mounted() {
    // 获取聊天容器引用
    this.chatContainer = this.$refs.chatContainer;
    this.getUserAvatarId();
    // 可以在这里添加初始化逻辑，如加载历史记录
  },
  methods: {
    /**
     * 发送消息到后端
     */
    async sendMessage() {
      const message = this.inputMessage.trim();
      // 验证消息有效性
      if (!message || this.isLoading) return;

      // 添加用户消息到列表
      this.messages.push({
        sender: 'user',
        content: message,
        avatarId: this.avatarId || 'default'
      });

      // 清空输入框
      this.inputMessage = '';
      // 设置加载状态
      this.isLoading = true;

      // 滚动到底部
      this.scrollToBottom();

      // 添加AI正在输入状态
      const aiMessageIndex = this.messages.push({
        sender: 'ai',
        content: '',
        loading: true
      }) - 1;

      try {
        // 调用后端API - 符合RequestMessage对象结构
        const response = await receiveMessage2({
          message: message,
          userId: this.getUserId() // 获取当前用户ID
        });

        // 检查响应状态
        console.log("后端返回完整数据:", response);
        if (response.code === 200) {
          // 更新AI消息内容
          this.messages[aiMessageIndex] = {
            sender: 'ai',
            content: response.data,
            loading: false
          };
        } else {
          console.error("后端返回错误：code=" + response.code + ", msg=" + response.msg);
          throw new Error(response.msg || '获取AI回复失败');
        }
      } catch (error) {
        console.error('发送消息失败:', error);
        // 显示错误消息
        this.messages[aiMessageIndex] = {
          sender: 'ai',
          content: '抱歉，我暂时无法回应你的请求，请稍后再试。',
          loading: false
        };
      } finally {
        // 结束加载状态
        this.isLoading = false;
        // 滚动到底部
        this.scrollToBottom();
      }
    },

    /**
     * 滚动到最新消息
     */
    scrollToBottom() {
      setTimeout(() => {
        if (this.chatContainer) {
          this.chatContainer.scrollTop = this.chatContainer.scrollHeight;
        }
      }, 100);
    },

    /**
     * 清空聊天记录
     */
    clearChat() {
      if (confirm('确定要清空聊天记录吗？')) {
        this.messages = [];
      }
    },

    /**
     * 格式化消息内容（处理换行）
     */
    formatMessage(content) {
      return content ? content.replace(/\n/g, '<br>') : '';
    },

    /**
     * 获取当前用户ID（实际项目中请替换为真实逻辑）
     */
    getUserId() {
      // 示例：从本地存储获取用户ID
      return localStorage.getItem('userId') || '14f25502-378d-46e5-a40c-b16592811319';
    },
    getUserAvatar(avatarId) {
      // 1. 先查缓存，有则直接返回
      console.log(avatarId)
      if (this.avatarCache[avatarId] !== undefined) {
        return this.avatarCache[avatarId];
      }

      // 2. 无缓存则请求后端接口
      // 注意：后端接口参数是Integer类型，这里确保userId转为数字
      const id = Number(avatarId);
      const token = sessionStorage.getItem("token");
      axios.get(`http://localhost:8080/user/avatar/${id}`,{
        headers: {
          "token": token // 添加token到请求头
        }
      })
          .then(response => {
            // 后端返回的ResponseUtil结构：{ code, data, msg }
            if (response.data.code === 200) { // 假设ResponseEnum.OK的code是200
              const fullAvatarUrl = response.data.data.avatar;
              this.avatarCache[avatarId] = fullAvatarUrl;
            } else {
              // 接口返回失败（如用户不存在），使用默认头像
              this.avatarCache[avatarId] = this.defaultAvatar;
            }
          })
          .catch(error => {
            // 网络错误等异常情况，使用默认头像
            console.error(`获取用户${avatarId}头像失败`, error);
            this.avatarCache[avatarId] = this.defaultAvatar;
          });

      // 3. 先返回默认头像，接口请求完成后会自动更新为真实头像
      return this.defaultAvatar;
    },
    getUserAvatarId(){
      const token = sessionStorage.getItem("token");
      if (!token) {
        console.error("未登录，无法建立AI连接");
        this.$router.push('/login'); // 未登录则跳转到登录页
        return;
      }
      this.avatarId = this.parseUserIdFromToken(token);
    },
    parseUserIdFromToken(token) {
      try {
        const decoded = jwtDecode(token);
        console.log("解析后的token payload：", decoded);
        // 确保提取的字段与token中实际的用户ID字段一致
        const avatarId = decoded.userId || decoded.id || decoded.user_id;
        if (!avatarId) {
          console.error("token中未找到用户ID字段");
          return null;
        }
        return avatarId.toString(); // 转为字符串，避免数字类型问题
      } catch (error) {
        console.error("解析token失败：", error);
        return null;
      }
    },
  },

};
</script>

<style scoped>
.user-avatar .avatar-img {
  width: 100%;    /* 占满父容器宽度 */
  height: 100%;   /* 占满父容器高度 */
  border-radius: 50%; /* 圆形头像，与AI头像圆角一致 */
  object-fit: cover;  /* 保持图片比例，避免拉伸 */
  background-color: #e5e7eb; /* 图片加载前的占位背景，与用户头像容器背景一致 */
}
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-height: 100vh;
  background-color: #f9fafb;
  overflow: hidden;
  /* 重置默认边距，避免外部样式干扰 */
  margin: 0;
  padding: 0;
}

/* 头部样式 */
.chat-header {
  display: flex;
  align-items: center;
  padding: 0.5rem 1rem; /* 缩小头部内边距 */
  background-color: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  z-index: 10;
  min-height: auto; /* 取消最小高度限制 */
}

.avatar {
  width: 32px; /* 缩小头像尺寸 */
  height: 32px;
  border-radius: 50%;
  background-color: #4f46e5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0.75rem; /* 缩小头像右侧间距 */
  color: white;
}

.chat-header h1 {
  font-size: 1rem; /* 缩小标题字号 */
  font-weight: 600;
  color: #111827;
  margin: 0;
  flex: 1;
}

.header-controls {
  display: flex;
  gap: 0.3rem; /* 缩小按钮间距 */
}

.control-btn {
  background: none;
  border: none;
  width: 28px; /* 缩小按钮尺寸 */
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s ease;
}

.control-btn:hover {
  background-color: #f3f4f6;
  color: #111827;
}

/* 消息区域样式 */
.chat-messages {
  flex: 1;
  padding: 1rem; /* 缩小消息区域内边距 */
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1rem; /* 缩小消息间距 */
}

.empty-state {
  margin: auto;
  text-align: center;
  color: #6b7280;
  padding: 1rem; /* 缩小空状态内边距 */
}

.empty-state p {
  margin: 0 0 0.3rem 0; /* 缩小空状态文字间距 */
  font-size: 0.9rem; /* 缩小空状态文字字号 */
}

.empty-state .subtext {
  font-size: 0.8rem; /* 缩小空状态辅助文字字号 */
  color: #9ca3af;
}

.message-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.message {
  width: 100%;
  margin-bottom: 0.5rem; /* 缩小消息底部间距 */
}

.message-content {
  display: flex;
  align-items: flex-start;
  max-width: 80%;
}

.user-message .message-content {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message .message-content {
  margin-right: auto;
}

.message-avatar {
  width: 28px; /* 缩小头像尺寸 */
  height: 28px;
  border-radius: 50%;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 0.5rem; /* 缩小头像间距 */
}

.user-avatar {
  background-color: #e5e7eb;
  color: #4b5563;
}

.ai-avatar {
  background-color: #4f46e5;
  color: white;
}

.message-bubble {
  padding: 0.5rem 0.8rem; /* 缩小气泡内边距 */
  border-radius: 0.8rem; /* 调整气泡圆角 */
  line-height: 1.4;
  position: relative;
  max-width: 100%;
  word-wrap: break-word;
}

.user-message .message-bubble {
  background-color: #4f46e5;
  color: white;
  border-bottom-right-radius: 0.25rem;
}

.ai-message .message-bubble {
  background-color: white;
  color: #111827;
  border: 1px solid #e5e7eb;
  border-bottom-left-radius: 0.25rem;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.message-bubble p {
  margin: 0;
  white-space: pre-wrap;
}

/* 输入区域样式 */
.chat-input {
  padding: 0.5rem 1rem; /* 缩小输入区域内边距 */
  background-color: white;
  border-top: 1px solid #e5e7eb;
}

.chat-input form {
  display: flex;
  gap: 0.5rem; /* 缩小输入区域元素间距 */
  align-items: flex-end;
}

.chat-input textarea {
  flex: 1;
  padding: 0.5rem 0.8rem; /* 缩小输入框内边距 */
  border: 1px solid #e5e7eb;
  border-radius: 0.4rem; /* 调整输入框圆角 */
  resize: none;
  min-height: 36px; /* 缩小输入框最小高度 */
  max-height: 100px;
  font-family: inherit;
  font-size: 0.9rem; /* 缩小输入框字号 */
  line-height: 1.4;
  transition: border-color 0.2s ease;
}

.chat-input textarea:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.1);
}

.chat-input textarea::placeholder {
  color: #9ca3af;
}

.chat-input button {
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 0.4rem; /* 调整按钮圆角 */
  width: 36px; /* 缩小按钮尺寸 */
  height: 36px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.chat-input button:hover {
  background-color: #4338ca;
}

.chat-input button:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

/* 打字动画 */
.typing-indicator {
  display: flex;
  gap: 0.2rem; /* 缩小打字动画点间距 */
  padding: 0.2rem 0;
}

.dot {
  width: 6px; /* 缩小打字动画点尺寸 */
  height: 6px;
  border-radius: 50%;
  background-color: #6b7280;
  animation: typing 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-content {
    max-width: 90%;
  }

  .chat-header, .chat-input {
    padding: 0.5rem 0.8rem;
  }

  .chat-messages {
    padding: 0.8rem;
  }

  .message-avatar {
    width: 24px;
    height: 24px;
    margin: 0 0.4rem;
  }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 4px; /* 缩小滚动条宽度 */
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>